#include <time.h>
#include <iostream>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>

using namespace std;
#define SIZE 1024

#define Info 0
#define Debug 1
#define Warning 2
#define Error 3
#define Fatal 4

#define Screen 1
#define Onefile 2
#define Classfile 3 

#define logfile "log.txt"

class log
{
public:
    log()
    {
        path = "./log/";
        printmethod = 1;
    }
    const char* option(int point)
    {
        switch (point)
        {
        case Info:
            return "Info";
        case Debug:
            return "Debug";
        case Warning:
            return "Warning";
        case Error:
            return "Error";
        case Fatal:
            return "Fatal";
        default:
            return "None";
        }
    }

    //打印日志信息的三种方式具体实现
    void printscreen(const char* logmessege)
    {
        printf("%s\n",logmessege);              
    }
    void printonefile(const string& filename,const char* logmessege)
    {
        string logpath = path+filename;
        int fd = open(logpath.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0666);
        if (fd<0)
        {
            perror("open");
            exit(-1);
        }
        //写
        write(fd,logmessege,strlen(logmessege));
        close(fd);
    }
    void printclassfile(int point, const char* logmessege)
    {
        string logpath = logfile;
        (logpath+='.')+=option(point);

        printonefile(logpath,logmessege);
    }

    //选取打印日志的方式
    void printflow(int point, const char* logmessege)
    {
        switch (printmethod)
        {
        case Screen:
            printscreen(logmessege);
            break;
        case Onefile:
            printonefile(logfile,logmessege);
            break;
        case Classfile:
            //实际上就是改了文件名然后复用printonefile
            printclassfile(point,logmessege);
            break;
        
        default:
            break;
        }
    }

    void logprint(int point, const char *format, ...)
    {
        //日志左边字符串
        char leffbuff[SIZE];
        time_t t = time(nullptr);
        struct tm *pt = localtime(&t);

        snprintf(leffbuff, SIZE, "[%s][%d-%d-%d-%d-%d-%d]",option(point), pt->tm_year + 1900, 
        pt->tm_mon + 1, pt->tm_mday, pt->tm_hour, pt->tm_min, pt->tm_sec);

        //日志右边字符串
        char rightbuff[SIZE];
        va_list s;
        va_start(s,format);
        vsnprintf(rightbuff,SIZE,format,s);

        //合并成为最终日志信息
        char logmessege[SIZE*2];
        snprintf(logmessege,SIZE*2,"%s%s\n",leffbuff,rightbuff);
        //printf("%s\n",logmessege);
        printflow(point, logmessege);

    }
    ~log()
    {
    }

private:
    string path;
    int printmethod;
};